package com.kancy.spring.aop;

import java.lang.reflect.Method;

/**
 * AroundAdvice
 *
 * @author kancy
 * @date 2020/2/19 1:36
 */
public class AroundAdvice implements Advice {
    private Object target;
    private AopAspect aspect;

    public AroundAdvice(Object target, AopAspect aspect) {
        this.target = target;
        this.aspect = aspect;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        if (!method.toString().matches(aspect.pointCut())){
            return method.invoke(target, args);
        }
        // 拦截方法执行
        Object result = null;
        JoinPoint joinPoint = null;
        try {
            joinPoint = new JoinPoint(proxy, target, method, args);
            aspect.before(joinPoint);
            result = aspect.invoke(joinPoint);
            aspect.after(joinPoint);
        } catch (Exception e) {
            aspect.afterThrowing(joinPoint);
        }finally {
            aspect.afterReturning(joinPoint);
        }
        return result;
    }
}
